<template>
    <div class="city-search">
            <input class="search-input" v-model="keyword" type="input" placeholder="输入城市名或拼音" />
            <div class="search-list" ref="wrapper" v-show="keyword">
                <ul>
                    <li class="search-item" v-for="item of list" :key="item.id" @click="changeCity(item.name)">{{item.name}}</li>
                    <li class="search-item" v-show="noData">暂无数据</li>
                </ul>
            </div>
    </div>
</template>

<script>
import BScroll from 'better-scroll'
export default {
  name: 'CitySearch',
  props: {
    cities: Object
  },
  data () {
    return {
      keyword: '',
      list: [],
      timer: null
    }
  },
  methods: {
    changeCity (city) {
      this.$store.commit('changeCity', city)
      this.$router.push('/')
    }
  },
  computed: {
    noData () {
      return !this.list.length
    }
  },
  watch: {
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyword) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        const result = []
        for (const key in this.cities) {
          this.cities[key].forEach(item => {
            if (item.name.indexOf(this.keyword) > -1 || item.spell.indexOf(this.keyword) > -1) {
              result.push(item)
            }
          })
        }
        this.list = result
      }, 100)
    }
  },
  mounted () {
    this.scroll = new BScroll(this.$refs.wrapper)
  },
  activated () {
    this.keyword = ''
  }
}
</script>

<style scoped>
.city-search {
    background: #00bcd4;
    height: .72rem;
    padding: 0 .1rem;
}
.search-input {
    box-sizing: border-box;
    width: 100%;
    height: .62rem;
    line-height: .62rem;
    text-align: center;
    border-radius: .06rem;
    padding: 0 .1rem;
    color: #666;
}
.search-list {
    overflow: hidden;
    position: absolute;
    top: 1.6rem;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1;
    background: #f6f6f6;
}
.search-item {
    padding:.25rem .2rem;
    border-bottom: .02rem solid #f6f6f6;
    background: #fff;
}
</style>
